const process = require('process');
const fs = require('fs');
const redeployEverytime = new Set((process.env['CI_REDEPLOY_EVERYTIME'] || "").split(","));
const self = process.env['CI_PROJECT_PATH'];

// ci-deployment.js <deployments.json> <ns> <repository> <tag>
const json = process.argv[2];
const ns = process.argv[3];
const repository = process.argv[4];
const tag = process.argv[5];

const deployments = JSON.parse(fs.readFileSync(json).toString());
for (const item of deployments.items) {
    for (const container of item.spec.template.spec.containers) {
        if (container.image === `${repository}:${tag}` && ns === item.metadata.namespace) {
            if (("Always" === container.imagePullPolicy && container.image.endsWith(":latest")) || redeployEverytime.has(self)) {
                // helm3 will upgrade imagePullPolicy to Always for latest
                // but will not redeploy if it is already Always + latest
                // or
                // test containers has been triggered
                console.log(item.metadata.name);
            }
        }
    }
}